//
//  HMNetworkTools.swift
//  06-Swift网络请求封装
//
//  Created by apple on 17/3/27.
//  Copyright © 2017年 itheima. All rights reserved.
//

import UIKit
import AFNetworking
//  网络请求的类型, 在swift里面枚举是可以指定的类型的
enum RequestType: Int {
    //提示: 枚举名需要使用小写
    //  get请求
    case get = 0
    //  post请求
    case post = 1
}

//  封装网络工具类
class HMNetworkTools: AFHTTPSessionManager {
    //  单例的全局访问点
    static let sharedTools: HMNetworkTools = {
        let tools = HMNetworkTools()
        //  添加AFN可以接收数据类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        //  添加AFN可以接收数据类型text/plain
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
   
    /// 封装网络请求的通用方法
    ///
    /// - Parameters:
    ///   - type: 请求类型
    ///   - urlStr: 请求地址
    ///   - params: 请求参数
    ///   - finishCallBack: 回调数据
    fileprivate func request(type: RequestType, urlStr: String, params: Any?, finishCallBack: @escaping (Any?, Error?)->()) {
        if type == .post {
            // '_'不这个参数,可以使用'_'把其忽略掉
            post(urlStr, parameters: params, progress: nil, success: { (_, response) in
                //  成功的回调
                finishCallBack(response, nil)
            }, failure: { (_, error) in
                //  失败的回调
                finishCallBack(nil, error)
            })
        } else {
            get(urlStr, parameters: params, progress: nil, success: { (_, response) in
                //  成功的回调
                finishCallBack(response, nil)
            }, failure: { (_, error) in
                //  失败的回调
                finishCallBack(nil, error)
            })
        }
        
    }
    
}


//  MARK: --- 首页相关接口
extension HMNetworkTools {
    
    /// 发送带图片的微博内容
    ///
    /// - Parameters:
    ///   - accessToken: 令牌
    ///   - status: 内容
    ///   - pic: 图片
    ///   - finishCallBack: 数据回调
    func sendWeiboMessage(accessToken: String, status: String, pic: UIImage, finishCallBack: @escaping (Any?, Error?)->()) {
        //  请求地址
        let urlStr = "https://upload.api.weibo.com/2/statuses/upload.json"
        //  请求参数
        let params = [
            "access_token": accessToken,
            "status": status
        ]
        // compressionQuality 图片的质量系数,系数越大图片对应的二进制数据越大, 如果对图片质量要求不高,可以把系统设置小一点
        let imageData = UIImageJPEGRepresentation(pic, 0.5)!
//        let imageData1 = UIImagePNGRepresentation(pic)!
//        try! imageData.write(to: URL(fileURLWithPath: "/Users/apple/Desktop/1.jpg"))
//        try! imageData1.write(to: URL(fileURLWithPath: "/Users/apple/Desktop/2.jpg"))
        post(urlStr, parameters: params, constructingBodyWith: { (formData) in
            //  withFileData: 图片二进制
            //  name : 服务端的参数
            //  filename: 文件名,可以随意写,服务端一般不会用,服务端自己生成文件名
            //  mimeType: 资源类型
            formData.appendPart(withFileData: imageData, name: "pic", fileName: "test", mimeType: "image/jpeg")
        }, progress: nil, success: { (_, response) in
            finishCallBack(response, nil)
        }) { (_, error) in
            finishCallBack(nil, error)
        }
        
    }
    
    /// 发送文字微博
    ///
    /// - Parameters:
    ///   - accessToken: 令牌
    ///   - status: 文字内容
    ///   - finishCallBack: 数据回调
    func sendWeiboMessage(accessToken: String, status: String, finishCallBack: @escaping (Any?, Error?)->()) {
        //  请求地址
        let urlStr = "https://api.weibo.com/2/statuses/update.json"
        //  请求参数
        let params = [
            "access_token": accessToken,
            "status": status
        ]
        //  发起网络请求
        request(type: .post, urlStr: urlStr, params: params, finishCallBack: finishCallBack)
    }
    
    /// 获取当前登录用户及其所关注（授权）用户的最新微博
    ///
    /// - Parameters:
    ///   - accessToken: 令牌
    ///   - finishCallBack: 回调数据
    func requestHomeData(accessToken: String, maxId: Int64 = 0, sinceId: Int64 = 0, finishCallBack: @escaping (Any?, Error?)->()) {
        //  请求地址
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        print(urlStr + "?access_token=\(accessToken)")
        
        //  请求参数
        let params: [String: Any] = [
            "access_token": accessToken,
            "max_id": maxId,
            "since_id": sinceId
        ]
        //  发送网络请求
        request(type: .get, urlStr: urlStr, params: params, finishCallBack: finishCallBack)
    }
    
}

//  MARK: --- OAuth登录相关接口
extension HMNetworkTools {
    
    
    /// 通过accessToken和uid获取用户信息
    ///
    /// - Parameters:
    ///   - accessToken: 令牌
    ///   - uid: 用户id
    ///   - finishCallBack: 数据回调
    func requestUserInfo(accessToken: String, uid: Int64, finishCallBack: @escaping (Any?, Error?)->()) {
        //  请求地址
        let urlStr = "https://api.weibo.com/2/users/show.json"
        print(urlStr + "?access_token=\(accessToken)&uid=\(uid)")
        //  请求参数
        let params: [String: Any] = [
            "access_token": accessToken,
            "uid": uid
        ]
        //  发送网络请求
        request(type: .get, urlStr: urlStr, params: params, finishCallBack: finishCallBack)
    }
    
    /// 通过code获取accesstoken
    ///
    /// - Parameters:
    ///   - code: 授权码
    ///   - finishCallBack: 数据回调
    func requestAccessToken(code: String, finishCallBack: @escaping (Any?, Error?)->()) {
        //  请求地址
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        //  请求参数
        let params: [String: Any] = [
            "client_id": AppKey,
            "client_secret": AppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": Redirect_Uri
        ]
        //  发送网络请求
        request(type: .post, urlStr: urlStr, params: params, finishCallBack: finishCallBack)
    }
}



